﻿// <copyright file="DropDownListExtensions.cs" company="Edge Extensions Project">
// Copyright (c) 2009 All Rights Reserved
// </copyright>
// <author>Kevin Nessland</author>
// <email>kevinnessland@gmail.com</email>
// <date>2009-07-08</date>
// <summary>Contains DropDownList-related extension methods.</summary>
namespace Edge.Extensions.Web
{
    using System;
    using System.Web.UI.WebControls;

    /// <summary>
    /// Provides various DropDownListExtensions.
    /// </summary>
    public static class DropDownListExtensions
    {
        /// <summary>
        /// Adds a blank item to the list.
        /// </summary>
        /// <param name="value">The DropDownList to work with.</param>
        public static void AddBlankItem(this DropDownList value)
        {
            ListItem li = new ListItem(String.Empty);
            value.Items.Insert(0, li);
            value.SelectedIndex = 0;
        }

        /// <summary>
        /// Adds an item to the list.
        /// </summary>
        /// <param name="value">The DropDownList to work with.</param>
        /// <param name="val">The value to add.</param>
        /// <param name="text">The text representation of the value.</param>
        public static void AddItem(this DropDownList value, string val, string text)
        {
            ListItem li = new ListItem(text, val);
            value.Items.Insert(0, li);
            value.SelectedIndex = 0;
        }

        /// <summary>
        /// Selects a DropDownList item.  If the selected item isn't found by
        /// value, it will attempt to select the item by its text.
        /// </summary>
        /// <param name="value">The DropDownList to work with.</param>
        /// <param name="val">The value of the item to select.</param>
        public static void SelectItem(this DropDownList value, string val)
        {
            ListItem li = value.Items.FindByValue(val);
            
            if (li != null)
            {
                value.SelectedValue = li.Value;

                value.SelectedItem.Text = li.Text;
            }
            else
            {
                li = value.Items.FindByText(val);

                if (li != null)
                {
                    value.SelectedValue = li.Value;

                    value.SelectedItem.Text = li.Text;
                }
            }
        }
    }
}
